package com.younge.spring.service;

import com.younge.spring.api.param.TableListParam;
import com.younge.spring.repository.DemoReponsitory;
import com.younge.spring.repository.dao.Demo;
import jakarta.persistence.criteria.Predicate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysService {
    private final DemoReponsitory demoReponsitory;

    public SysService(DemoReponsitory demoReponsitory) {
        this.demoReponsitory = demoReponsitory;
    }

    public Page<Demo> getTableList(TableListParam tableListParam) {
        Pageable pageable = PageRequest.of(tableListParam.getPage() - 1, tableListParam.getPageSize());
        Specification<Demo> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            String category = tableListParam.getCategory();
            if (category != null && !category.isBlank()) {
                predicates.add(cb.equal(root.get("category"), category));
            }
            String productName = tableListParam.getProductName();
            if (productName != null && !productName.isBlank()) {
                predicates.add(cb.equal(root.get("productName"), productName));
            }
            BigDecimal price = tableListParam.getPrice();
            if (price != null) {
                predicates.add(cb.equal(root.get("price"), price));
            }
            String color = tableListParam.getColor();
            if (color != null && !color.isBlank()) {
                predicates.add(cb.equal(root.get("color"), color));
            }
            String date = tableListParam.getDate();
            if (date != null && !date.isBlank()) {
                predicates.add(cb.equal(root.get("date"), date));
            }

            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return demoReponsitory.findAll(spec, pageable);
    }
}
